package org.example;


import java.util.*;
        import java.util.concurrent.*;

public class SimpleRaft {
    enum NodeState {
        FOLLOWER, CANDIDATE, LEADER
    }

    static class RaftNode {
        private int nodeId;
        private NodeState state;
        private List<String> log;
        private int currentTerm;
        private Map<Integer, NodeState> votes;
        private ExecutorService executor;

        public RaftNode(int nodeId) {
            this.nodeId = nodeId;
            this.state = NodeState.FOLLOWER;
            this.log = new ArrayList<>();
            this.currentTerm = 0;
            this.votes = new HashMap<>();
            this.votes.put(nodeId, NodeState.FOLLOWER);
            this.executor = Executors.newSingleThreadExecutor();
        }

        public void startElection() {
            executor.submit(() -> {
                state = NodeState.CANDIDATE;
                currentTerm++;
                votes.clear();
                votes.put(nodeId, state);
                System.out.println(nodeId + " started an election for term " + currentTerm);
                // 在这里实现请求投票的逻辑
                // 简化实现：直接假设自己赢得了选举
                state = NodeState.LEADER;
                System.out.println(nodeId + " won the election for term " + currentTerm);
            });
        }

        public void run() {
            // 模拟追随者和领导者的行为
            while (true) {
                if (state == NodeState.FOLLOWER) {
                    // 追随者行为：监听领导者的心跳和命令
                } else if (state == NodeState.LEADER) {
                    // 领导者行为：发送心跳，处理日志
                }
                try {
                    Thread.sleep(100); // 简化实现：每100毫秒检查一次状态
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void appendEntry(String entry) {
            // 追加日志条目
            log.add(entry);
        }

        public void applyEntry(String entry) {
            // 应用日志条目
        }

        public void shutdown() {
            executor.shutdownNow();
        }
    }

    public static void main(String[] args) {
        RaftNode node1 = new RaftNode(1);
        RaftNode node2 = new RaftNode(2);
        RaftNode node3 = new RaftNode(3);

        // 启动节点
        node1.startElection();
        node2.startElection();
        node3.startElection();

        // 运行节点
        node1.run();
        node2.run();
        node3.run();
    }
}
//加注释调试